var get=require('../../../utils/getRequest');
var post=require('../../../utils/postRequest');
const api= require('../../../utils/api')
const ecUI = require('../../../utils/ecUI.js')
const ecBLE = require('../../../utils/ecBLE.js')
let ctx
let isCheckRevHex = false
let isCheckScroll = true
let isCheckSendHex = false
Page({
  data: {
      deviceListData: [],
      deviceListDataShow: [],
      deviceSn:null,
      productList:[],
      deviceMsg:null,
      sheetShow:false,
      sheetActions:[],
      textRevData: '',
      productOptions:[], 
      popupShow:false,
      note:null,
      fieldValue: '',
      gridList:[],
        index:0
  },
  onLoad(options) {
    var deviceSn=options.deviceSn;
      ctx = this
      ctx.setData({deviceSn:deviceSn});
      setInterval(() => {
          ctx.setData({ deviceListDataShow: ctx.data.deviceListData })
      }, 400)
      get.getRequest(null,api.getAllProductList,{}).then(res=>{
            ctx.setData({productList:res.data});
            ctx.getDevice();
      });
  },
  getDevice(){
    var data={deviceSn:ctx.data.deviceSn}
    get.getRequest(null,api.getDeviceByDeviceSn,data).then(res=>{
     ctx.setData({deviceMsg:res.data});
     ctx.initGrids();
     ctx.setProductOptions();
     ctx.initSheetActions();
    });
  },
  initSheetActions(){
    var deviceMsg=this.data.deviceMsg;
    var gridNumber=deviceMsg.gridNumber;
    var sheetActions=[];
    for(var i=1;i<=gridNumber;i++){
      sheetActions.push({id:"0"+i,name:"第"+i+"格子"});
    }
    this.setData({sheetActions:sheetActions})
  },
  initGrids(){
    var deviceMsg=this.data.deviceMsg;
    var gridNumber=deviceMsg.gridNumber;
    var gridList=[];
    console.log("格子数："+gridNumber);
    for(var i=1;i<=gridNumber;i++){
      var name="第"+i+"格";
      var note="选择服务状态";
      var str="grid0"+i+"ProductId";
      var obj=deviceMsg[str].split(",");
      var dictname=this.dictName(obj[0]);
      var productName=this.productName(obj[1]);
      name=name+"("+dictname+"/"+productName+")"
      gridList.push({name:name,note:note});
    }
    console.log("初始化：",gridList);
    this.setData({gridList:gridList});
  },
  setProductOptions(){
    var gridList=ctx.data.gridList;
    var deviceMsg=ctx.data.deviceMsg;
    var productOptions=[{label:'正常服务',value:'1',},{label:'停止服务',value:'2',}];
    for(var i=0;i<gridList.length;i++){
      var index=i+1;
      var name="grid0"+index+"StateType";
      var value=deviceMsg[name];
      console.log("值："+value);
      for(var j=0;j<productOptions.length;j++){
        console.log("值2："+productOptions[j].value);
        if(productOptions[j].value==value){
          gridList[i].note=productOptions[j].label;
        }
      }
    }    
    ctx.setData({
              productOptions:productOptions,
              gridList:gridList
            });
  },
  dictName(StateType){
      if(StateType=="1"){
        return '出售'
      }else if(StateType=="2"){
        return '出租'
      }
  },
  productName(ProductId){
    var productList=this.data.productList;
    for(var i=0;i<productList.length;i++){
      if(productList[i].productId==ProductId){
        return productList[i].productName;
      }
    }
  },
  saveRepairFlag(){
    var data={
      deviceSn:this.data.deviceSn,
      repairFlag: 'N'
    }
    wx.showLoading({title:'保存处理中'});
    get.getRequest(null,api.saveDevcieRepairFlag,data).then(res=>{
      wx.showModal({
        title: '提示信息',
        showCancel:false,
        content: res.msg
      })
    }).finally(res=>{
      wx.hideLoading();
    })
  },
  showCascader(e) {
    console.log(e);
    var index=e.currentTarget.dataset.index;
    this.setData({ popupShow: true,index:index });
  },
  onPick(e) {
    console.log(e.detail);
  },
  onChange(e) {
    console.log("------------------------");
    console.log(e);
    const { selectedOptions, value } = e.detail;
    
    var note=selectedOptions.map((item) => item.label).join('/');
    var index=this.data.index;
    var gridList=this.data.gridList;
    gridList[index].note=note;
    var data={
      index:index,
      deviceSn:ctx.data.deviceSn,
      stateType:selectedOptions[0].value
    }
    console.log(data)
    wx.showLoading({title:'保存处理中'});
    get.getRequest(null,api.saveDevcieGridState,data).then(res=>{
      if(res.code==200){
        ctx.setData({gridList:gridList});
        wx.showModal({
          title: '提示信息',
          showCancel:false,
          content: res.msg
        })
      }else{
        wx.showModal({
          title: '提示信息',
          showCancel:false,
          content: res.msg
        })
      }
    }).finally(res=>{
      wx.hideLoading();
    })
    

    /* this.setData({
      fieldValue:value,
      note: selectedOptions.map((item) => item.label).join('/'),
    }); */
  },
  onSheetSelect(e){
    var index=e.detail.id;
    console.log("index======="+index);
    var commd='{\"lock\":\"'+index+'\"'+'}';
    console.log("commd======="+commd);
    ctx.btSendTap(commd);
  },
  showSheet(){
    this.setData({sheetShow:true})
    },
  onSheetClose(){
      this.setData({sheetShow:false})
    },
  onShow() {
      ctx.setData({ deviceListData: [] })
      ctx.setData({ deviceListDataShow: [] })
      ctx.openBluetoothAdapter()
/*       setTimeout(() => {
          ctx.openBluetoothAdapter()
      }, 100) */
  },
  onPullDownRefresh: function () {
      ctx.setData({ deviceListData: [] })
      ctx.setData({ deviceListDataShow: [] })
      setTimeout(() => {
          wx.stopPullDownRefresh()
          ctx.openBluetoothAdapter()
      }, 500)
  },
  listViewTap(device) {
      ecUI.showLoading('设备连接中')
      ecBLE.onBLEConnectionStateChange(res => {
          ecUI.hideLoading()
          if (res.ok) {
              ecBLE.stopBluetoothDevicesDiscovery()
              //wx.navigateTo({ url: '../device/device' })
          } else {
              ecUI.showModal(
                  '提示',
                  '连接失败,errCode=' + res.errCode + ',errMsg=' + res.errMsg
              )
          }
      })
      //const device = event.currentTarget.dataset.name
      ecBLE.createBLEConnection(device.id).then(res=>{
            ctx.onState();
            ecUI.hideLoading();
      });
  },
  onState(){
        isCheckScroll = true
        isCheckRevHex = false
        isCheckSendHex = false
    //on disconnect
    ecBLE.onBLEConnectionStateChange(() => {
     // ecUI.showModal('提示', '设备断开连接')
  })
  //receive data
  ecBLE.onBLECharacteristicValueChange((str, strHex) => {
      let data =isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str
      console.log(data)
      //ctx.setData({ textRevData: data })
  })
  },
  btSendTap(sendData) {
        let tempSendData = sendData.replace(/\n/g, '\r\n')
        ecBLE.writeBLECharacteristicValue(tempSendData, false)
},
  openBluetoothAdapter() {
      ecBLE.onBluetoothAdapterStateChange(res => {
          if (res.ok) {
              console.log('Bluetooth adapter ok')
              ctx.startBluetoothDevicesDiscovery()
          } else {
              ecUI.showModal(
                  '提示',
                  `Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
                  () => {
                      if (res.errCode === 30001) {
                          wx.openSystemBluetoothSetting()
                      }
                      if (res.errCode === 30003) {
                          wx.openAppAuthorizeSetting()
                      }
                      if (res.errCode === 30004) {
                          //跳转到小程序设置界面
                          wx.openSetting()
                      }
                  }
              )
          }
      })
      ecBLE.openBluetoothAdapter()
  },
  startBluetoothDevicesDiscovery() {
      console.log('start search')
      ecBLE.onBluetoothDeviceFound(res => {
          // if(res.id==="EC:22:05:13:78:49")
          // console.log(`id:${res.id},name:${res.name},rssi:${res.rssi}`)
          for (const item of ctx.data.deviceListData) {
              if (item.id === res.id) {
                  item.name = res.name
                  item.rssi = res.rssi
                  return
              }
          }
          let manufacturer = ''
          if (res.name.length === 11 && res.name.startsWith('@')) {
              manufacturer = 'eciot'
          }
          if (res.name.length === 15 && res.name.startsWith('BT_')) {
              manufacturer = 'eciot'
          }
          if(res.name==ctx.data.deviceSn){
              ctx.data.deviceListData.push({
                  id: res.id,
                  name: res.name,
                  rssi: res.rssi,
                  manufacturer,
              })
              ctx.listViewTap(res);
            }
      })
      ecBLE.startBluetoothDevicesDiscovery()
  },
      /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
      ecBLE.onBLEConnectionStateChange(() => { })
      ecBLE.onBLECharacteristicValueChange(() => { })
      ecBLE.closeBLEConnection()
  },
})
